//获取客户端ip地址
const getClientIp = (req) => {
    var ip =
        req.headers["x-forwarded-for"] ||
        req.ip ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress ||
        "";
    if (ip.split(",").length > 0) {
        ip = ip.split(",")[0];
    }
    ip = ip.substr(ip.lastIndexOf(":") + 1, ip.length);
    return ip;
};

const state = () => {
    return {
        token: "",
        currency: "USD", // 币种
        rate: 1, // 汇率
        ready: false,
    };
};
const getters = {
    // 是否已经登录
    getIsLogin(state) {
        return !!state.token;
    },
    // token
    getToken(state) {
        return state.token;
    },
};

const mutations = {
    // 重置币种
    SET_CURRENCY(state, payload) {
        const option = payload || {};
        state.currency = option.currency || "USD";
        state.rate = option.rate || 1;
        this.$cookiz.set("currency", state.currency, {
            maxAge: 60 * 60 * 24 * 7,
            path: "/",
        });
    },
};
const actions = {
    // 跨页面通讯发消息
    sendTokenMessage(store, token) {
        const msg = JSON.stringify({ token: token });
        localStorage.setItem("_message", msg);
        setTimeout(() => localStorage.removeItem("_message"), 100);
    },

    // 登录
    async doLogin(store, token) {
        if (token == store.state.token) {
            // 相同的不管
            // 假装已经登录完成
        } else {
            const res = await this.$http(
                "getUserInfo",
                { source: "login" },
                { token: token }
            );
            if (res.code == 0) {
                this.$cookiz.set("token", token, {
                    maxAge: 60 * 60 * 24 * 7,
                    path: "/",
                });
                store.state.token = token;
                store.dispatch("user/setUserInfo", res.data);
                store.dispatch("sendTokenMessage", token);
            } else {
                return Promise.reject(res.msg);
            }
        }
    },

    // 退出
    async doLogout(store) {
        if (!store.state.token) {
            // 已经退出了
        } else {
            store.state.token = "";
            this.$cookiz.remove("token", { path: "/" });
            store.dispatch("user/removeUserInfo");
            store.dispatch("sendTokenMessage", "");
        }
    },

    // 获取汇率
    getCurrency(store, currency) {
        return this.$http("Resource.getCurrency/" + currency).then((res) => {
            // 切换币种
            const data = res.data || {};
            if (res.code === 0 && data.rate) {
                store.commit("SET_CURRENCY", data);
            } else {
                store.commit("SET_CURRENCY", { currency: "USD", rate: 1 });
            }
        });
    },

    async getUserInfoOnServe(store, payload) {
        const res = await this.$http("getUserInfo", { source: "node" });
        if (res.code == 0) {
            store.dispatch("user/setUserInfo", res.data);
        } else {
            store.state.token = "";
            this.$cookiz.remove("token", { path: "/" });
        }
    },

    // 这个函数只在store/index.js中生效，其他位置不生效
    async nuxtServerInit(store, { app, req }) {
        // 如果有token，则取user信息
        const token = this.$cookiz.get("token") || "";
        const currency = this.$cookiz.get("currency") || "USD";
        const promises = [];

        // 获取分类数据
        promises.push(store.dispatch("common/getProductClassify"));

        // console.log(req.headers["x-forwarded-for"], getClientIp(req));

        // 品牌数据
        // promises.push(store.dispatch("common/getProductBrand"));

        // 有token时
        if (token) {
            // 设置token
            store.state.token = token;
            // 获取用户数据
            promises.push(store.dispatch("getUserInfoOnServe"));

            // promises.push(store.dispatch("getCurrency", currency));
        } else if (currency != "USD") {
            // 获取汇率
            promises.push(store.dispatch("getCurrency", currency));
        }

        await Promise.all(promises);
    },
};

export default {
    strict: false,
    state,
    getters,
    mutations,
    actions,
};
